<?php

namespace Acme\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

use Acme\UserBundle\Entity\CmUser;
use Acme\UserBundle\Entity\CmUserInfo;
use Acme\UserBundle\Entity\ConstUniversity;

use Acme\UserBundle\Form\UserInfoType;
use Acme\UserBundle\Form\UserManageType;
use Acme\UserBundle\Form\UserCreateType;


/**
 * @Route("/admin/user_manage")
 */
class UserCRUDController extends Controller
{
    /**
     * @Route("", name="AcmeUserBundle_UserSearch")
     * @Template()
     */
    public function indexAction() {
    	/*$temp = $this->get('security.context')->getToken()
    				->getUser()->getUserInfo()->getUniversityInfo();
    	echo "<pre>";
    	print_r($temp);*/
    	$buildOption['role'] = $this->get('security.context')->getToken()->getUser()->getRoles();
    	$form = $this->createForm(new UserManageType(), '', $buildOption);
        return array('form' => $form->createView());
    }
    
    /**
     * @Route("/create", name="AcmeUserBundle_UserCreate")
     * @Template()
     */
    public function createAction() {
    	$user = new CmUser();
    	$buildOption['role'] = $this->get('security.context')->getToken()->getUser()->getRoles();
    	$form = $this->createForm(new UserCreateType(), $user, $buildOption);
    	return array('form' => $form->createView());
    }
    
    /**
     * @Route("/list", name="AcmeUserBundle_UserList")
     * @Template()
     */
    public function listAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition = $request->get('user_manage');
    		
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] = 
    				$this->get('security.context')->getToken()
    				->getUser()->getUserInfo()->getUniversity();
    		}
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    		
    		return array('users' => $user);
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/info", name="AcmeUserBundle_UserInfo")
     * @Template()
     * TODO
     */
    public function infoAction() {
    	$request = $this->get('request');
    	
    	$userInfo = new CmUserInfo();  // The form should be created by Owning Side
    	
    	$buildOption['build_for'] = 'edit';
    	$form = $this->createForm(new UserInfoType(), $userInfo, $buildOption);
    	
    	return array("form" => $form->createView());
    }
    
    /**
     * @Route("/verify", name="AcmeUserBundle_UserVerify")
     * @Template()
     */
    public function verifyAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition['id'] = $request->get('id');
    		$result = $request->get('result');
    		
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] =
	    			$this->get('security.context')->getToken()
	    			->getUser()->getUserInfo()->getUniversity();
    		}
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    		
    		if (!$user) {
    			throw $this->createNotFoundException('No user found for id ' . $condition['id']);
    		}
    		
    		$userStatusEn = $this->container->getParameter('userStatusEn');
    		if ($userStatusEn[$user->getUserStatus()] == 'to-verify') {
    			$user->setUserStatus(array_search($result, $this->container->getParameter('userStatusEn')));
    			$em->flush();
    			return new Response('success');
    		}
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/edit", name="AcmeUserBundle_UserEdit")
     * @Template()
     */
    public function editAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		
    		if ($request->get('id')) {
    			$condition['id'] = $request->get('id');
    			
    			if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    				$condition['university'] =
    					$this->get('security.context')->getToken()
    					->getUser()->getUserInfo()->getUniversity();
    			}
    			
    			if ($request->get('show_modal_request')) {
    				$em = $this->getDoctrine()->getEntityManager();
    				$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    				//echo "<pre>";
    				//print_r($user);
    				if (!$user) {
    					throw $this->createNotFoundException('No user found for id ' . $condition['id']);
    				}
    				
    				$userCategoryEn = $this->container->getParameter('userCategoryEn');
    				$category_name = $userCategoryEn[$user->getCategory()];
    				
    				$userInfo = new CmUserInfo();  // The form should be created by Owning Side
    				
    				$buildOption['category_name'] = $category_name;
    				$buildOption['build_for'] = 'edit';
    				$form = $this->createForm(new UserInfoType(), $userInfo, $buildOption);
    				
    				return array('form' => $form->createView(), 'user' => $user);
    			} else {
    				/**
    				 * TODO flush posts
    				 */
    				return new Response('success');
    			}
    		} else {  // create new user
    			$form_data = $request->get('user_create');
    			//echo "<pre>";
    			//print_r($form_data);
    			if ($this->get('security.context')->isGranted('ROLE_SUPER_ADMIN')) {
    				$userCategoryEn = $this->container->getParameter('userCategoryEn');
    			} else {
    				$userCategoryEn = $this->container->getParameter('universityUserCategoryEn');
    			}
    			
    			if (key_exists($form_data['userCategory'], $userCategoryEn)) {
    				$em = $this->getDoctrine()->getEntityManager();
    				$user = new CmUser();
    				$userInfo = new CmUserInfo();
    				
    				if ($this->get('security.context')->isGranted('ROLE_SUPER_ADMIN')) {
	    				$universityInfo = $em->getRepository('AcmeCommonBundle:ConstUniversity')
	    					->find($form_data['university']);
    				} else {
    					$universityInfo = $this->get('security.context')->getToken()->getUser()->getUserInfo()->getUniversityInfo();
    				}
    				if (!$universityInfo) {
    					throw $this->createNotFoundException('No university found for id');
    				}
    				
    				$user->setUsername($form_data['username']);
    				
    				// load encoderfactory and set salt encoded password for user
    				$factory = $this->get('security.encoder_factory');
    				$encoder = $factory->getEncoder($user);
    				
    				$security_helper = new \Acme\SecurityBundle\SecurityHelper();
    				$plaintext_password = '19910319';//$security_helper->generatePassword();
    				
    				$password = $encoder->encodePassword($plaintext_password, $user->getSalt());
    				$user->setPassword($password);
    				
    				$user->setEmail($form_data['email']);
    				$user->setCategory($form_data['userCategory']);
    				$userInfo->setUser($user);
    				
    				if ($userCategoryEn[$form_data['userCategory']] != 'outsider') {
    					$userInfo->setUniversityInfo($universityInfo);
    				}
    				
    				$em->persist($user);
    				if ($userCategoryEn[$form_data['userCategory']] != 'outsider') {
    					$em->persist($userInfo);
    				}
    				
    				$em->flush();
    				
    				$this->get('mail_manager')->userCreate($user, $plaintext_password);
    				return new Response('success');
    			}
    		}
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/delete", name="AcmeUserBundle_UserDelete")
     */
    public function deleteAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition['id'] = $request->get('id');
    		
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] =
    				$this->get('security.context')->getToken()
    				->getUser()->getUserInfo()->getUniversity();
    		}
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    		
    		if (!$user) {
    			throw $this->createNotFoundException('No user found for id ' . $condition['id']);
    		}
    		
    		$user->setFlag(array_search('is-delete', $this->container->getParameter('flagEn')));
    		if ($user->getUserInfo()) {
    			$user->getUserInfo()->setFlag(array_search('is-delete', $this->container->getParameter('flagEn')));
    		}
    		$em->flush();
    		return new Response('success');
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/undelete", name="AcmeUserBundle_UserUndelete")
     */
    public function undeleteAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition['id'] = $request->get('id');
    		
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] =
    				$this->get('security.context')->getToken()
    				->getUser()->getUserInfo()->getUniversity();
    		}
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    		
    		if (!$user) {
    			throw $this->createNotFoundException('No user found for id ' . $condition['id']);
    		}
    
    		$user->setFlag(array_search('not-delete', $this->container->getParameter('flagEn')));
    		if ($user->getUserInfo()) {
    			$user->getUserInfo()->setFlag(array_search('not-delete', $this->container->getParameter('flagEn')));
    		}
    		$em->flush();
    		return new Response('success');
    	}
    	throw $this->createNotFoundException();
    }
}
